/*
 * Copyright 2009 André Luiz Alves Moraes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * */



package org.alamoraes.codegen.template;

import java.util.Hashtable;
import java.util.Map;
import org.alamoraes.codegen.IGetMethodExtension;
import org.alamoraes.codegen.IMethodExtender;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.InvalidReferenceEventHandler;
import org.apache.velocity.context.Context;
import org.apache.velocity.util.introspection.Info;

/**
 * Implements the method extender to add custom properties
 * @author andre
 */
public class MethodExtenderImpl implements IMethodExtender {
    
    private Map<String, IGetMethodExtension> extendProperties;

    /**
     * Constructor
     */
    public MethodExtenderImpl() {
        extendProperties = new Hashtable<String, IGetMethodExtension>(10, 0.7f);
    }

    /**
     * Returns the extend properties map
     * @return
     */
    public Map<String, IGetMethodExtension> getExtendedProperties() {
        return extendProperties;
    }

    /**
     * Extends the Velocity Event Cartrige adding the registred extended properties
     * Only adds read-only (get) properties
     * @param cartrige
     */
    public void extendCartrige(EventCartridge cartrige) {
        cartrige.addInvalidReferenceEventHandler(new InvalidReferenceEventHandler() {

            public Object invalidGetMethod(Context context, String reference, Object object, String property, Info info) {
                if (property == null)
                    return null;
                
                if (getExtendedProperties().containsKey(property)) {
                    return getExtendedProperties().get(property).extend(context, reference, object, info);
                } else {
                    return null;
                }
            }

            public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info) {
                return false;
            }

            public Object invalidMethod(Context context, String reference, Object object, String method, Info info) {
                return null;
            }
        });
    }

    /**
     * Register a extended property
     * @param getMethod
     */
    public void registerGet(IGetMethodExtension getMethod) {
        getExtendedProperties().put(getMethod.getPropertyName(), getMethod);
    }

}
